<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>地图</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <script src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="./underscore.js"></script>
    <script type="text/javascript"
            src="https://webapi.amap.com/maps?v=1.4.15&key=08ab42f891f38908e56f759eae92f06a"></script>
    <style>
        .map-container {
            position: relative;
        }

        body {
            padding: 0;
            margin: 0
        }

        #map {
            height: 600px;
        }

        .su-marker {
            padding: 10px;
            line-height: 2;
            font-size: 13px;
            padding-top: 0;
        }

        .su-marker span {

        }

        .map-type a {
            font-size: 13px;
            text-align: center;
            width: 60px;
            line-height: 1.7;
            box-shadow: 0px 0px 3px 1px #0000007d;
            border-radius: 3px;
            margin-bottom: 10px;
            cursor: pointer;
            background: #fff;
            color: #444;
            display: block;
            text-decoration: none
        }

        .list-item {
            width: 200px;
            line-height: 2;
            border: 1px solid #3c99f4;
        }

        .list-item span {
            display: inline-block;
            min-width: 50px;
            color: #777;
            font-size: 13px;
        }

        .list-item label {
            font-weight: bold;
            color: #333;
            font-size: 13px;
            display: inline-block;
            width: 40px;
            padding-left: 10px;
        }

        .sum-tips, .schedule-tips, .project-tips, .tips {
            position: absolute;
            display: none;
            background: #ffffffe0;
            bottom: 50px;
            z-index: 9999;
            padding: 10px;
            box-shadow: 2px 0px 4px 1px #607d8ba3;
            border-radius: 0;
            left: 0;
            margin: 0 auto;
            font-size: 14px;
            color: #666;
            text-align: left;
            line-height: 2;
        }

        .tips .title {
            text-align: center;
            color: #2196F3;
            font-weight: bold;
        }

        .tips label {
            font-weight: bold;
            color: #333;
            font-size: 13px;
            display: inline-block;
            width: 50px;
            padding-left: 0px;
        }

        .schedule-tips label {
            width: 130px;
        }

        .tips label.active {
            color: #2196F3
        }

        .project-tips label {
            width: 60px;
        }

        .sum-tips {
            left: 230px;
            min-width: 150px;
            z-index: 9999;
        }

        .schedule-tips {
            left: 230px;
            display: none;
        }

        .footer .btn {
            text-decoration: none;
        }

        .footer {
            line-height: 3;
        }
    </style>
</head>
<body>
<div
        class="map-container"
>
    <div
            id="map"
            class="map"
    ></div>
    <div class="project-tips tips">
        <div class="title">项目概览</div>
        <div class="content" style="max-width: 200px;    border: 1px solid gray;
    padding: 5px;">
            <!--            <label>项目名称</label> 勘察项目勘察项目勘察项目勘察项目 <br/>-->
            <!--            <label>项目状态</label> 勘察中 <br/>-->
            <!--            <label>项目编号</label> 123123123 <br/>-->
            <!--            <label>创建时间</label> 2020.03.04 <br/>-->
            <!--            <label>创建人</label> 苏伟明 <br/>-->
        </div>
        <div class="footer">
            <a class="btn" href="javascript:void(0);">勘探点统计</a>
            <a class="btn" href="javascript:void(0);">进度计划</a>
        </div>

    </div>
    <div class="sum-tips tips">
    </div>
    <div class="schedule-tips tips">

    </div>
</div>
</body>
<script type="text/javascript">
    var domain = 'http://192.168.31.39:8080',
    // var domain = 'http://1.85.30.164:8821',
        tileLayer, map;
    $(function () {
        function parseSearch(search) {
            var resultObj = {};
            var search = search || window.location.search;
            if (search && search.length > 1) {
                var search = search.indexOf('?') == 0 ? search.substring(1) : search;
                var items = search.split('&');
                for (var index = 0; index < items.length; index++) {
                    if (!items[index]) {
                        continue;
                    }
                    var kv = items[index].split('=');
                    if (resultObj[kv[0]] != undefined) {
                        if ($.isArray(resultObj[kv[0]])) {
                            // resultObj[kv[0]].push(decodeURI(kv[1])); // 解码
                            resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                        } else {
                            // var ar = [resultObj[kv[0]],decodeURI(kv[1])];
                            resultObj[kv[0]] += ',' + decodeURI(kv[1]);
                        }
                    } else {
                        resultObj[kv[0]] = typeof kv[1] === "undefined" ? "" : decodeURI(kv[1]); // 解码
                    }
                }
            }
            return resultObj;
        }
        var  searchObj =parseSearch(window.location.search);
        var floatTool = function () {
            /*
             * 判断obj是否为一个整数
             */
            function isInteger(obj) {
                return Math.floor(obj) === obj
            }

            /*
             * 将一个浮点数转成整数，返回整数和倍数。如 3.14 >> 314，倍数是 100
             * @param floatNum {number} 小数
             * @return {object}
             *   {times:100, num: 314}
             */
            function toInteger(floatNum) {
                var ret = {times: 1, num: 0}
                if (isInteger(floatNum)) {
                    ret.num = floatNum
                    return ret
                }
                var strfi = floatNum + ''
                var dotPos = strfi.indexOf('.')
                var len = strfi.substr(dotPos + 1).length
                var times = Math.pow(10, len);
                var isFu = floatNum < 0;
                var intNum = parseInt(Math.abs(floatNum) * times + 0.5, 10)
                ret.times = times
                if (isFu) {
                    ret.num = -intNum
                } else {
                    ret.num = intNum
                }
                return ret
            }

            /*
             * 核心方法，实现加减乘除运算，确保不丢失精度
             * 思路：把小数放大为整数（乘），进行算术运算，再缩小为小数（除）
             *
             * @param a {number} 运算数1
             * @param b {number} 运算数2
             * @param digits {number} 精度，保留的小数点数，比如 2, 即保留为两位小数
             * @param op {string} 运算类型，有加减乘除（add/subtract/multiply/divide）
             *
             */
            function operation(a, b, op) {
                var o1 = toInteger(a)
                var o2 = toInteger(b)
                var n1 = o1.num
                var n2 = o2.num
                var t1 = o1.times
                var t2 = o2.times
                var max = t1 > t2 ? t1 : t2
                var result = null
                switch (op) {
                    case 'add':
                        if (t1 === t2) { // 两个小数位数相同
                            result = n1 + n2
                        } else if (t1 > t2) { // o1 小数位 大于 o2
                            result = n1 + n2 * (t1 / t2)
                        } else { // o1 小数位 小于 o2
                            result = n1 * (t2 / t1) + n2
                        }
                        return result / max
                    case 'subtract':
                        if (t1 === t2) {
                            result = n1 - n2
                        } else if (t1 > t2) {
                            result = n1 - n2 * (t1 / t2)
                        } else {
                            result = n1 * (t2 / t1) - n2
                        }
                        return result / max
                    case 'multiply':
                        result = (n1 * n2) / (t1 * t2)
                        return result
                    case 'divide':
                        return result = function () {
                            var r1 = n1 / n2
                            var r2 = t2 / t1
                            return operation(r1, r2, 'multiply')
                        }()
                }
            }

            // 加减乘除的四个接口
            function add(a, b) {
                return operation(a, b, 'add')
            }

            function subtract(a, b) {
                return operation(a, b, 'subtract')
            }

            function multiply(a, b) {
                return operation(a, b, 'multiply')
            }

            function divide(a, b) {
                return operation(a, b, 'divide')
            }

            return {
                add: add,
                subtract: subtract,
                multiply: multiply,
                divide: divide
            }
        }();
        var TaskStatus = {
            NEED_ASSIGN: 0,//待分配
            NEED_DESC: 1,//待描述
            NEED_CHECK: 2,//待验收,
            NEED_RESOLVE: 3,//验收通过,
            NEED_REJECTED: 4,//验收不通过,
            labelFn: (type) => {
                console.log(type);
                return type == 0 ? '待分配' : (type == 1 ? '待描述' : (type == 2 ? '待验收' : (type == 3 ? '验收通过' : (type == 4 ? '验收不通过' : '未设置'))));
            },
        }

        function convert(gps) {
            return new Promise((resolve, reject) => {
                window.AMap && window.AMap.convertFrom && window.AMap.convertFrom(gps, 'gps', function (status, result) {
                    if (result.info === 'ok') {
                        var lnglats = result.locations; // Array.<LngLat>
                        resolve(lnglats);
                    }
                });
            })
        }

        map = new AMap.Map('map', {
            zoom: 17,    //级别
            resizeEnable: true,
            zooms: [4, 18],//设置地图级别范围
            layers: [],
            center: [109.004514, 34.25147],//中心点坐标
        });
        // 同时引入工具条插件，比例尺插件和鹰眼插件
        AMap.plugin([
            'AMap.ToolBar',
            'AMap.Scale',
            'AMap.OverView',
            'AMap.MapType',
        ], function () {
            // 在图面添加工具条控件，工具条控件集成了缩放、平移、定位等功能按钮在内的组合控件
            map.addControl(new AMap.ToolBar());
            // 在图面添加比例尺控件，展示地图在当前层级和纬度下的比例尺
            map.addControl(new AMap.Scale());

            // 在图面添加鹰眼控件，在地图右下角显示地图的缩略图
            map.addControl(new AMap.OverView({isOpen: true}));

            // 在图面添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
            map.addControl(new AMap.MapType());
        });
        AMap.plugin('AMap.ToolBar', function () {//异步加载插件
            var toolbar = new AMap.ToolBar();
            map.addControl(toolbar);
        });
        var ProjectStatus = {
            PROGRESSING: '1',//勘察中
            END: '2',//已终止
            ARCHIVE: '0',//已归档,
            labelFn: (type) => {
                return type == 1 ? '勘察中' : (type == 2 ? '已终止' : '已归档');
            },
        };

        $('.project-tips .footer a').click(function () {
            if ($(this).index() == 0) {
                if ($('.sum-tips').css('display') == 'block') {
                    $('.sum-tips').hide();
                } else {
                    $('.sum-tips').show();
                    $('.schedule-tips').hide();
                }

            } else {
                if ($('.schedule-tips').css('display') == 'block') {
                    $('.schedule-tips').hide();
                } else {
                    $('.sum-tips').hide();
                    $('.schedule-tips').show();
                }
            }
        })
        $.get(domain + '/api/v1/task/mapData/'+searchObj.id, function (res) {
            res.list = res.data.tasks;
            var center = [0, 0], latlngs = [], lists = res.list;

            var project = res.data.project;
            var content = ' <label>项目名称</label> ' + project.name + ' <br/>\n' +
                '            <label>项目状态</label> ' + ProjectStatus.labelFn(project.status) + ' <br/>\n' +
                '            <label>项目编号</label> ' + project.no + ' <br/>\n' +
                '            <label>创建时间</label> ' + project.createAt.slice(0, 10) + ' <br/>\n' +
                '            <label>创建人</label> ' + project.creatorName + ' <br/>';
            $('.project-tips .content').html(content);
            $('.project-tips').show();
            res.list.map(item => {
                item.lonLat = item.lonLat.split(',');
                center[0] = floatTool.add(center[0], parseFloat(item.lonLat[0]))
                center[1] = floatTool.add(center[1], parseFloat(item.lonLat[1]))
                latlngs.push(new AMap.LngLat(parseFloat(item.lonLat[0]), parseFloat(item.lonLat[1])));
            })
            var statusObj = _.groupBy(res.list, 'status');
            var num = res.list.length,
                num1 = (statusObj[TaskStatus.NEED_ASSIGN] || []).length,
                num2 = (statusObj[TaskStatus.NEED_RESOLVE] || []).length;
            $('.sum-tips').replaceWith('<div class="sum-tips tips">\n' +
                '<div class="title">勘探点统计</div>\n' +
                '<label>勘探点</label>' + num + '个 <br/>\n' +
                '<label>未分配</label>' + (num - num1 - num2) + '个<br/>' +
                '<label>待描述</label>' + num1 + '个<br/>' +
                '<label>已完工</label>' + num2 + '个<br/>' +
                '<label class="active">完工率</label>' + (parseFloat((num2 / num).toFixed(2)) * 100) + '%<br/>' +
                '<label class="active">执行中</label>' + (parseFloat((num1 / num).toFixed(2)) * 100) + '%' +
                '    </div>');
            if (!project.plans) {
                $('.schedule-tips').replaceWith('<div class="schedule-tips tips">\n' +
                    '<div class="title">未设置进度计划</div>\n' +
                    '</div>');
            } else {
                project.plans = JSON.parse(project.plans);
                $('.schedule-tips').replaceWith('<div class="schedule-tips tips">\n' +
                    '<div class="title">进度计划</div>\n' +
                    '<label>外业进度计划</label>' +
                    project.plans.time1Start.slice(0, 10) + '至' + project.plans.time1End.slice(0, 10) + ' <br/>\n' +
                    '<label>室内试验进度计划</label>' +
                    project.plans.time2Start.slice(0, 10) + '至' + project.plans.time2End.slice(0, 10) + ' <br/>\n' +
                    '<label>报告书编制进度计划</label>' +
                    project.plans.time3Start.slice(0, 10) + '至' + project.plans.time3End.slice(0, 10) + '<br/>' +
                    '<label>报告书审核审定计划</label>' +
                    project.plans.time4Start.slice(0, 10) + '至' + project.plans.time4End.slice(0, 10) + '<br/>' +
                    '    </div>');
            }

            //添加到地图
            convert(latlngs)
                .then(function (res) {
                    map.clearMap();
                    var i = 0;
                    res.map(function (item) {
                        var icon = new AMap.Icon({
                            // 图标尺寸
                            size: new AMap.Size(22, 22),
                            // 图标的取图地址
                            image: '//a.amap.com/jsapi_demos/static/demo-center/marker/marker.png',
                            // 图标所用图片大小
                            imageSize: new AMap.Size(22, 22),
                        })

                        var marker = new AMap.Marker(Object.assign({
                            position: [item.lng, item.lat]//位置,
                        }, lists[i].status == TaskStatus.NEED_RESOLVE ? {icon: icon,} : {}));
                        var circleMarker = new AMap.CircleMarker({
                            center: [item.lng, item.lat],
                            radius: 10,//3D视图下，CircleMarker半径不要超过64px
                            strokeColor: 'white',
                            strokeWeight: 2,
                            strokeOpacity: 0.5,
                            fillColor: 'rgba(0,0,255,1)',
                            fillOpacity: 0.5,
                            zIndex: 10,
                            bubble: true,
                            cursor: 'pointer',
                            clickable: true
                        })
                        // circleMarker.setMap(map)
                        map.add(marker);
                        var content = [
                            "<div class='su-marker'>" +
                            "<div>勘探点详情</div>"
                            + [
                                '<div class="list-item" style="border-bottom: none">' +
                                '<label>孔号 </label><span>' + lists[i].no + '</span>' +
                                '<label>孔性 </label><span>' + lists[i].type + '</span>' +
                                '</div>' +
                                '<div class="list-item" style="border-bottom: none">' +
                                '<label>状态 </label><span>' + TaskStatus.labelFn(lists[i].status) + '</span>' +
                                '<label>标高 </label><span>' + lists[i].height + 'm</span>' +
                                '</div>' +
                                '<div class="list-item" style="border-bottom: none">' +
                                '<label>孔深 </label><span>' + lists[i].depth + 'm</span>' +
                                '</div>' +
                                '<div class="list-item">' +
                                '<label>时间 </label>' + lists[i].createAt + '' +
                                '</div>'
                            ].join('')
                            + "</div>"
                        ];
                        i++;
                        var infoWindow = new AMap.InfoWindow({
                            anchor: 'bottom-center',
                            content: content.join(""),
                            offset: new AMap.Pixel(0, -30)
                        });

                        AMap.event.addListener(marker, 'click', function () {
                            $('.sum-tips').hide();
                            $('.schedule-tips').hide();
                            infoWindow.open(map, marker.getPosition());
                        });
                    })
                    map.setFitView();
                })

            // center[0] = (center[0] / res.list.length);
            // center[1] = (center[1] / res.list.length);
            // convert(new AMap.LngLat(center[0], center[1]))
            //     .then(function (center) {
            //         map.panTo([center[0].lng, center[0].lat]);
            //     })
            // map.setFitView();
        })
    })
</script>
</html>
